<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
        <el-alert
            title="添加商品信息"
            :closable="false"
            type="info"
            center
            show-icon>
        </el-alert>

        <!-- :active中的值是一个数字,索引从0开始 -->
        <el-steps :space="200" :align-center="true" :active="activeIndex-0" finish-status="success">
            <el-step title="基本信息"></el-step>
            <el-step title="商品参数"></el-step>
            <el-step title="商品属性"></el-step>
            <el-step title="商品图片"></el-step>
            <el-step title="商品内容"></el-step>
            <el-step title="完成"></el-step>
        </el-steps>

        <el-form label-position='top' :model="addGoodsForm" :rules="addGoodsRules" ref="addGoodsRef" label-width="100px" class="demo-ruleForm">
            <el-tabs @tab-click='tabHandleClick' :before-leave='beforeLeave' tab-position="left" v-model="activeIndex" >
                <el-tab-pane label="基本信息" name="0">
                     <el-form-item label="商品名称" prop="goods_name">
                         <el-input v-model="addGoodsForm.goods_name"></el-input>
                     </el-form-item>
                     <el-form-item label="商品价格" prop="goods_price">
                         <el-input type='number' v-model="addGoodsForm.goods_price"></el-input>
                     </el-form-item>
                      <el-form-item  label="商品重量" prop="goods_weight">
                         <el-input type='number' v-model="addGoodsForm.goods_weight"></el-input>
                     </el-form-item>
                     <el-form-item label="商品数量" prop="goods_number">
                         <el-input type='number' v-model="addGoodsForm.goods_number"></el-input>
                     </el-form-item>
                     <el-form-item label="商品分类" prop="goods_number">
                         <el-cascader
                            v-model="selectCascaderOptArr"
                            :options="cascaderList"
                            :props="cascaderProps"
                            @change="cascaderHandleChange"
                            >
                        </el-cascader>
                     </el-form-item>
                </el-tab-pane>
                <el-tab-pane label="商品参数" name="1">
                    <el-form-item v-for='(item,i) in manyData' :label='item.attr_name' :key='i'>
                        <el-checkbox-group v-model='item.attr_vals'>
                            <el-checkbox border name='type' v-for="(item2,i) in item.attr_vals" :key='i' :label="item2"></el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>
                </el-tab-pane>
                <el-tab-pane label="商品属性" name="2">
                    <el-form-item v-for='(item,i) in onlyData' :key='i' :label='item.attr_name'>
                        <el-input v-model='item.attrs'></el-input>
                    </el-form-item>
                </el-tab-pane>
                <el-tab-pane label="商品图片" name="3">
                    <el-upload
                        class="upload-demo"
                        action="http://127.0.0.1:8888/api/private/v1/upload"
                        :headers='setHeader'
                        :on-preview="handlePreview"
                        :on-remove="handleRemove"
                        
                        :on-success='handleSuccess'
                        list-type="picture">
                        <el-button size="small" type="primary">点击上传</el-button>
                    </el-upload>
                </el-tab-pane>
                <el-tab-pane label="商品内容" name="4">
                    <quill-editor v-model="addGoodsForm.goods_introduce">
                    </quill-editor>
                    <el-button @click="handleAddGoods" type='primary'>添加商品</el-button>
                </el-tab-pane>
            </el-tabs>
        </el-form>
    </el-card>
    <!--  -->
    <el-dialog
    title="提示"
    :visible.sync="imgDialogVisible"
    width="50%"
    >
    <img style="width:100%;" :src="imgurl" alt="">
    <!-- <span>这是一段信息</span>
        <span slot="footer" class="dialog-footer">
            <el-button @click="imgDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
        </span> -->
    </el-dialog>
  </div>
</template>

<script>
export default {

  data () {
    return {
        activeIndex:0,
        addGoodsForm:{
            goods_name:'test',
            goods_price:10,
            goods_weight:200,
            goods_number:20,
            pics:[],
            goods_introduce:'',
            attrs:[],
            goods_cat:''
        },
        cascaderProps:{
            expandTrigger: 'hover',
            // 展示的选项名称
            label:'cat_name',
            // 和v-model绑定的数组对应,是数组中的每一项对应的id
            value:'cat_id'
        },
        // 级联v-model绑定的数据:保存用户选择的级联项
        selectCascaderOptArr:[1,4,23],
        // 级联模块props关联的源数据
        cascaderList:[],
        // 表单验证规则
        addGoodsRules:{
            goods_name:[{ required: true, message: '请输入商品名称', trigger: 'blur' }],
            goods_price:[{ required: true, message: '请输入商品价格', trigger: 'blur' }],
            goods_weight:[{ required: true, message: '请输入商品重量', trigger: 'blur' }],
            goods_number:[{ required: true, message: '请输入商品数量', trigger: 'blur' }]
        },
        manyData:[],
        onlyData:[],
        setHeader:{
            Authorization:sessionStorage.getItem('token')
        },
        imgDialogVisible:false,
        imgurl:''
    }
  },

  methods: {
        // 该方法用于级联框中的展示的分类数据
      async getcascaderList(){
          const res=await this.axios.get('categories');
          if(res.meta.status==200){
              this.cascaderList=res.data
          }
        //   console.log(this.cascaderList);
      },
    //   切换标签之前的钩子函数
      beforeLeave(n,o){
        // console.log(o);
          if(o==0){
              if(this.selectCascaderOptArr.length!=3){
                  this.$mg.error('请选择商品分类');
                //   befeore-leave要求返回的值是false时,阻止页面切换
                  return false;
              }
          }
      },
      async tabHandleClick(){
        //   console.log(this.activeIndex);
         if(this.activeIndex=='1'){
              const res=await this.axios.get(`categories/${this.selectCascaderOptArr[2]}/attributes`,{
              params:{
                  sel:'many'
              }
          })
            res.data.forEach(item=>{
                item.attr_vals=item.attr_vals?item.attr_vals.split(','):[];
            })

            if(res.meta.status==200){
                this.manyData=res.data;
            }
         }else if(this.activeIndex=='2'){
              const res=await this.axios.get(`categories/${this.selectCascaderOptArr[2]}/attributes`,{
              params:{
                  sel:'only'
              }
          })
            res.data.forEach(item=>{
                item.attr_vals=item.attr_vals?item.attr_vals.split(','):[];
            })

            if(res.meta.status==200){
                this.onlyData=res.data;
            }
         }
         console.log(this.onlyData);
         
      },
    //   
    cascaderHandleChange(){
        console.log(this.selectCascaderOptArr);
    },
    // 处理图片显示与隐藏
    handlePreview(file){    
        // console.log(typeof file.response.data.url);
        this.imgurl=file.response.data.url;        
        this.imgDialogVisible=true;
    },

    handleRemove(file){
        // console.log(file);
        var filePath=file.response.data.tmp_path;
        var index=this.addGoodsForm.pics.findIndex(item=>{
            return item.pic==filePath        
        })
        console.log(index);
        this.addGoodsForm.pics.splice(index,1);
        console.log(this.addGoodsForm.pics);        
    },

    handleSuccess(res){
        console.log(res);
        if(res.meta.status==200){
            this.$mg.success('图片上传成功!')
            this.addGoodsForm.pics.push({
                pic:res.data.tmp_path
            })
        }
        console.log(this.addGoodsForm.pics);
    },
    
    handleAddGoods(){
        this.addGoodsForm.goods_cat=this.selectCascaderOptArr.join(',');
        // console.log(this.addGoodsForm);
        
        this.manyData.forEach(item=>{
            this.addGoodsForm.attrs.push({
                attr_id:item.attr_id,
                attr_value:item.attr_vals.join(',')
            });
        })
        // console.log(this.addGoodsForm);
        
        this.onlyData.forEach(item=>{
            this.addGoodsForm.attrs.push({
                attr_id:item.attr_id,
                attr_value:item.attr_vals
            });
        })
        // console.log(this.addGoodsForm);

        this.$refs.addGoodsRef.validate(async flag=>{
            if(!flag) return this.$mg.error('请输入表单数据');

            const res=await this.axios.post(`goods`,this.addGoodsForm);
            if(res.meta.status==201){
                this.$mg.success('添加商品成功!');
                this.$router.push('/goods');
            }else{
                this.$mg.success('添加商品失败!');
            }
        })

    }

  },

  created () {
      this.getcascaderList();
  }
}
</script>

<style lang='less' scoped>
.el-steps{
    margin:15px 0;
}
.el-button{
    margin: 10px 0; 
} 
</style>
